package com.bjsxt.shop.back.springmvc.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsBrand;
import com.bjsxt.shop.goods.pojo.AGoodsBrandEnum;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.pojo.AGoodsCateEnum;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AAdmins;

/**
 * URL规划,拦截器拦截
 * @author WangshSxt
 *
 */
@Controller
@RequestMapping("/back/goods/")
public class GoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/**
	 * 品牌列表
	 * @return
	 */
	@RequestMapping("/brandList")
	public String brandList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandList--");
		return "/back/goods/brandList" ; 
	}
	
	/**
	 * 品牌列表--返回JSON数据
	 * 
	 * {
	 * 	"total":28,
	 * 	"rows":
	 * 	[
			{"productid":"AV-CB-01","productname":"Amazon Parrot","unitcost":92.00,"status":"P","listprice":63.50,"attr1":"Adult Male","itemid":"EST-18"}
		]}

	 * 
	 * @return
	 */
	@RequestMapping(value = "/brandListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(String page,String rows)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandListJSON--");
		String[] pages = page.split(",");
		page = pages[0];
		String[] rowss = rows.split(",");
		rows = rowss[0];
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 查询列表 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
		/* 数据 */
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		
		/* 拼装数据,json */
		JSONObject resultJSON = new JSONObject() ;
		resultJSON.put("total", totalRecord);
		
		/* 数据 */
		JSONArray dataArr = new JSONArray() ; 
		int count = 1 ; 
		for (Iterator iterator = brandList.iterator(); iterator.hasNext();)
		{
			AGoodsBrand brand = (AGoodsBrand) iterator.next();
			JSONObject brandJSON = brand.toJSON();
			brandJSON.put("count", count);
			
			/* brand对象变成JSON */
			dataArr.add(brandJSON);
			count ++ ;
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString(); 
	}
	
	/**
	 * 品牌添加
	 * @return
	 */
	@RequestMapping("/brandInsert")
	public String brandInsert()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsert--");
		return "/back/goods/brandInsert" ; 
	}
	
	/**
	 * 品牌添加提交
	 * @return 返回JSON
	 * {
	 * 	"code":"0",
	 * 	"info":"",
	 * }
	 */
	@RequestMapping(value = "/brandInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(String pubtimeStr,AGoodsBrand goodsBrand,HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsertSubmit--");
		JSONObject resultJSON = new JSONObject() ; 
		
		/* 自己来转换时间,就不用转换器了 */
		goodsBrand.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		/* 把页面上木有赋值的属性,赋值一下 */
		/* 从Session中获取 */
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		goodsBrand.setAdminsId(adminsSess.getId());
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		/* 保存数据 */
		resultJSON = this.goodsService.saveOneGoodsBrandService(goodsBrand);
		return resultJSON.toJSONString() ; 
	}

	/*商品模块开始*/
	/**
	 * 商品列表开始
	 * @return
	 */
	@RequestMapping("/goodsList")
	public String goodsList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---goodsList---");
		return "back/goods/goodsList";
	}
	
	
	@RequestMapping(value ="/goodsListJson",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJson(HttpServletRequest request,String page,String rows,String keyword,String status,String st,String ed)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---goodsListJson---");
		/* 处理get方式的乱码 */
		try
		{
			keyword = new String(keyword.getBytes("ISO8859-1"), "UTF-8");
		} catch (Exception e)
		{
			
		}
		/*分页信息*/
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		
		/*搜索条件*/
		if(status==null)
		{
			status="";
		}
		if(st==null)
		{
			st="";
		}
		if(ed==null)
		{
			ed="";
		}
		
		Date stDate =null;
		Date edDate =null;
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			//将开始时间，结束时间从String类型转换成date类型
			stDate = dateFormatUtil.strDateTime(st);
			edDate = dateFormatUtil.strDateTime(ed);
		}
		Map<String,Object> condMap = new HashMap<String,Object>();
		condMap.put("keyword", keyword);
		if(!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		/*查询列表*/
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		
		/*数据*/
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord")+"");
		
		/*拼装数据*/
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", totalRecord);
		
		/*数据*/
		JSONArray dateArr = new JSONArray();
		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goodsTemp = (AGoods) iterator.next();
			JSONObject brandJSON = goodsTemp.toJSON();
			
			/*brandJSON对象变成JSON*/
			dateArr.add(brandJSON);
		}
		resultJSON.put("rows", dateArr);
		return resultJSON.toJSONString();
	}
	
	/*品牌添加*/
	/**
	 * 品牌添加操作
	 */
	@RequestMapping("/goodsInsert")
	public String goodsInsert(Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=======goodsInsert====");
		/*查询所有启用的商品*/
		Map<String,Object> condMap = new HashMap<String, Object>();
		condMap.clear();
		condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(null, condMap);
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		/* 放到四大作用域中 */
		model.addAttribute("brandList",brandList);
		
		/*查询商品的分类*/
		List<AGoodsCate> goodsTreeListCate = this.goodsService.findTreeListCateService();
		/* 放到四大作用域中 */
		model.addAttribute("goodsTreeListCate",goodsTreeListCate);
		condMap.put("status", AGoodsCateEnum.STATUS_ENABLE.getStatus());
		
		return "/back/goods/goodsInsert";
	}
	
	/**
	 * 品牌添加操作提交
	 */
	
	@RequestMapping(value="/goodsInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsInsertSubmit(AGoods goods,String pubtimeStr,HttpSession session,HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("=======goodsInsertSubmit====");
		JSONObject jsonObject = new JSONObject();
		
		/*
		 * request.getParameter("spec_功能_制冷类型")
		 * [
				{
					"name": "功能",
					"keys": [
								{
									"name":"制冷类型",
									"values":"冷暖"
								}
							]
				}
			]
		 * */
		/*
		 * 是以分类为蓝本,
		 * 查询用户选择的分类
		 * */
		Map<String,Object> condMap = new HashMap<String,Object>();
		condMap.put("id", goods.getCateId());
		AGoodsCate goodsCate = this.goodsService.findOneGoodsCateService(condMap);
		JSONArray specArr = goodsCate.getSpecArr();
		for (Iterator iterator = specArr.iterator(); iterator.hasNext();)
		{
			JSONObject jsonTemp1 = (JSONObject) iterator.next();
			JSONArray keysArr = (JSONArray) jsonTemp1.get("keys");
			for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();)
			{
				JSONObject jsonkeyTemp2 = (JSONObject) iterator2.next();
				/* values从哪来? */
				String keyParam ="spec_"+jsonTemp1.get("name")+"_"+jsonkeyTemp2.get("name");
				/* key:是不确定的 */
				String value = request.getParameter("keyParam");
				jsonkeyTemp2.put("values", value);
			}
		}
		/* 将分类中的规格values由原来的数组变成了值 */
		goods.setSpec(specArr.toJSONString());
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		
		/*为页面上没有显示的字段赋值*/
		/* 自己来转换时间,就不用转换器了 */
		goods.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		
		/* 从Session中获取 */
		goods.setAdminsId(adminsSess.getId());
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		
		jsonObject = this.goodsService.saveOneGoodsService(goods);
		return jsonObject.toJSONString();
	}
	
	/*商品模块结束*/

}
